/*
 * File:   clientUDP.c
 * Author: dannv
 *
 * Created on October 23, 2009, 10:06 AM
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#define SERV_UDP_PORT 12356
#define SIZE 1024

/*
 * Afficher l'erreur et quiter le serveur
 */
void err_stop(msg) char *msg;
{
    perror(msg);
    exit(-1);
}

/*
 *
 */
int main(int argc, char** argv) {

    int sockfd, len, port;
    struct sockaddr_in serv_addr, client_addr;
    struct hostent *host;
    char buff[SIZE];

    // Prendre parametres
    if (argc < 2) {
        fprintf(stderr, "Client-Usage: %s <hostname> [port]\n", argv[0]);
        exit(1);
    }
     // prendre host et port info
    if ((host = gethostbyname(argv[1])) == NULL) {
        err_stop("Client-gethostbyname() error");
    }
    if (argc == 3) {
        sscanf(argv[2], "%d", &port);        
    } else {
        port = SERV_UDP_PORT;        
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
    serv_addr.sin_port = htons(port);

    // Ouvrir un sock_data socket
    if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
        err_stop("Open socket");
    }

    bzero((char *) &client_addr, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    client_addr.sin_port = htons(0);

    // Bind
    if (bind(sockfd, (struct sockaddr *) &client_addr, sizeof(client_addr)) < 0)
        err_stop("client: can't bind local address");   

    // Send bonjour
    sprintf(buff, "%s\0", "Bonjour");
    len = sizeof(serv_addr);
    if (sendto(sockfd, buff, strlen(buff), 0, (struct sockaddr *)&serv_addr, len) != strlen(buff)) {
        err_stop("client: sendto error");
    }

    // Recieve responses    
    int i = 0;
    for (i = 0; i < 61; i++) {
        alarm(61);
        if ((len = recvfrom(sockfd, buff ,SIZE ,0 ,(struct sockaddr *)0, (int *)0)) < 0) {
            if (errno == EINTR)
                err_stop("Socket timeout");
            else
                err_stop("Receive from server");
        }
        buff[len] = '\0';
        printf("Message from server : %s", buff);
    }
    shutdown(sockfd, 2);
    close(sockfd);

    return (EXIT_SUCCESS);
}


